const fs = require('fs')
const path = require('path')

class UploadController {
  static async uploadImage(ctx) {
    // 获取所有文件
    // console.log("ctx.request.files:", ctx.request.files)
    const filesObj = ctx.request.files || {}
    let { image } = filesObj  // key = image

    if (!image) {
      ctx.err({ message: "no image param" })
      return
    }

    const fileTypes = ['image/jpeg', 'image/png']
    if (!fileTypes.includes(image.mimetype)) {
      ctx.err({ message: "the image format is not 'jpg', 'jpeg', 'png'" })
      return
    }

    // 获取第一个文件
    const file = image
    // console.log("file:", file)

    // 读取上传的文件（文件会被koa-body上传至一个临时文件中）
    const reader = fs.createReadStream(file.filepath)

    // 要上传的目录路径
    const srcPath = __dirname.slice(0, __dirname.lastIndexOf("\\"))
    const suffix = file.originalFilename.substring(file.originalFilename.lastIndexOf('.'), file.originalFilename.length)
    console.log('sufixx:', suffix)
    const httpPath = ctx.origin + '/images/' + file.newFilename + suffix
    const writePath = path.join(srcPath, '/public/images/', file.newFilename + suffix)
    console.log("write path:", writePath)

    const writeStream = fs.createWriteStream(writePath)
    // 写入要上传的目录
    reader.pipe(writeStream)

    ctx.succ({
      data: {
        path: httpPath
      }
    })
  }
}

module.exports = {
  UploadController
}